package com.google.code.crawler.core;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public final class CrawlerRegistry
{
    private static ApplicationContext appCtx;

    private static final Logger LOGGER = LoggerFactory.getLogger(CrawlerRegistry.class);

    public static <T> T getBean(final Class<T> clazz)
    {

        initAppContext();

        return appCtx.getBean(clazz);

    }

    public static <T> Collection<T> getBeans(final Class<T> clazz)
    {

        initAppContext();

        Collection<T> results = Collections.emptyList();

        final Map<String, T> beansMap = appCtx.getBeansOfType(clazz);

        if (beansMap != null && !beansMap.isEmpty())
        {

            results = beansMap.values();

        }

        return results;

    }

    /**
     * Init the Application Context if it isn't already
     */
    private static void initAppContext()
    {
        if (appCtx == null)
        {
            LOGGER.info("Initializing application context for Crawler");
            appCtx = new ClassPathXmlApplicationContext("classpath:/crawler-spring.xml");
        }
    }
}
